import { defineStore } from 'pinia'
import { ref, watch } from 'vue'

export const useSettingsStore = defineStore('settings', () => {
  // 状态
  const theme = ref<'light' | 'dark'>('light')
  const language = ref<'zh-CN' | 'en-US'>('zh-CN')
  const notifications = ref(true)
  const autoSave = ref(true)

  // 从 localStorage 初始化
  const initSettings = () => {
    const savedTheme = localStorage.getItem('theme')
    const savedLanguage = localStorage.getItem('language')
    const savedNotifications = localStorage.getItem('notifications')
    const savedAutoSave = localStorage.getItem('autoSave')

    if (savedTheme) theme.value = savedTheme as 'light' | 'dark'
    if (savedLanguage) language.value = savedLanguage as 'zh-CN' | 'en-US'
    if (savedNotifications !== null) notifications.value = JSON.parse(savedNotifications)
    if (savedAutoSave !== null) autoSave.value = JSON.parse(savedAutoSave)
  }

  // 切换主题
  const toggleTheme = () => {
    theme.value = theme.value === 'light' ? 'dark' : 'light'
  }

  // 设置语言
  const setLanguage = (lang: 'zh-CN' | 'en-US') => {
    language.value = lang
  }

  // 切换通知
  const toggleNotifications = () => {
    notifications.value = !notifications.value
  }

  // 切换自动保存
  const toggleAutoSave = () => {
    autoSave.value = !autoSave.value
  }

  // 监听变化并保存到 localStorage
  watch(theme, (newTheme) => {
    localStorage.setItem('theme', newTheme)
    // 应用主题到 body
    document.body.className = newTheme === 'dark' ? 'dark' : ''
  })

  watch(language, (newLanguage) => {
    localStorage.setItem('language', newLanguage)
  })

  watch(notifications, (newNotifications) => {
    localStorage.setItem('notifications', JSON.stringify(newNotifications))
  })

  watch(autoSave, (newAutoSave) => {
    localStorage.setItem('autoSave', JSON.stringify(newAutoSave))
  })

  // 初始化
  initSettings()

  return {
    // 状态
    theme,
    language,
    notifications,
    autoSave,
    
    // 方法
    toggleTheme,
    setLanguage,
    toggleNotifications,
    toggleAutoSave,
    initSettings
  }
}) 